import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { CreateUserDto, UpdateUserDto } from './dto/user.dto';

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User)
        private userRepository: Repository<User>,
    ) { }

    async create(createUserDto: CreateUserDto) {
        const hashedPassword = await bcrypt.hash(createUserDto.password, 10);
        const newUser = this.userRepository.create({
            ...createUserDto,
            password: hashedPassword,
        });
        return this.userRepository.save(newUser);
    }

    findAll() {
        return this.userRepository.find();
    }

    findOne(id: number) {
        const user = this.userRepository.findOneBy({ id });
        if (!user) throw new NotFoundException()
        return user
    }

    async update(id: number, updateUserDto: UpdateUserDto) {
        const user = await this.userRepository.findOneBy({ id })
        if (!user) throw new NotFoundException()
        if (await bcrypt.compare(updateUserDto.oldPassword, user.password)) {
            const hashedPassword = await bcrypt.hash(updateUserDto.newPassword, 10);
            const { newPassword, oldPassword, ...newUser } = updateUserDto
            return this.userRepository.update(id, { ...newUser, password: hashedPassword });
        } else {
            throw new BadRequestException('user password incorrect')
        }
    }

    async remove(id: number) {
        const deleteResult = await this.userRepository.delete(id);
        if (deleteResult.affected == 0) throw new NotFoundException()
        return true
    }
}
